package com.lt.contract.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lt.contract.bean.NMContractNew;
import com.lt.contract.bean.NM_RENEW_CONTRACT;
import com.lt.contract.bean.utils.Constant;
import com.lt.contract.bean.utils.ExcelImport;
import com.lt.contract.dao.NMContractNewMapper;
import com.lt.contract.service.NMNewContractService;
import com.lt.report.service.AsyncService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class NMNewContractServiceImpl implements NMNewContractService {

    @Autowired
    NMContractNewMapper mapper;

    @Autowired
    AsyncService asyncService;

    @Override
    public String insertSelective(NMContractNew record) {
        if (mapper.getSerialNumberCount(record)>0){
            return Constant.serialNumberRepetition;
        }
        String code = String.valueOf(mapper.insertSelective(record));
        return code;
    }

    @Override
    public String updateByPrimaryKeySelective(NMContractNew record) throws Exception {
        //1.先判断该数据是否修改过电路号码
        //2.如果没有直接修改
        //3.如果有再判断该电路号码是否已经存在于表中
        NMContractNew contract =mapper.getUpdateSerialNumber(record);
        if (contract.getSerialNumber()==null){
            return String.valueOf(mapper.updateByPrimaryKeySelective(record));
        }else if(contract.getSerialNumber().equals(record.getSerialNumber())){
            return String.valueOf(mapper.updateByPrimaryKeySelective(record));
        }else if(mapper.getSerialNumberCount(record)>0){
            return Constant.serialNumberRepetition;
        }
        String code = String.valueOf(mapper.updateByPrimaryKeySelective(record));
        return code;
    }

    @Override
    public NMContractNew selectByPrimaryKey(String id) throws Exception {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<NMContractNew> queryNewContractList(Map<String, Object> map) throws Exception {
        return mapper.queryNewContractList(map);
    }

    @Override
    public Long getNewContractListCount(Map<String, Object> map) throws Exception {
        return mapper.getNewContractListCount(map);
    }

    @Override
    public int deleteByPrimaryKey(NMContractNew record) throws Exception {
        return mapper.deleteByPrimaryKey(record);
    }

    @Override
    public String getBankListByExcel(InputStream in, String fileName, String staffId) throws Exception {
        //选择文件中的列
        //创建Excel工作薄
        Workbook work = ExcelImport.getWorkbook(in, fileName);
        Sheet sheet = work.getSheetAt(0);
        List<Integer> column = Arrays.asList(0,1,2);
        String empty = ExcelImport.isEmpty(sheet, column);
        if(!empty.equals("true")){
            return empty;
        }
        List<String> isRecur = ExcelImport.isRecur(sheet,2);
        if(isRecur.size()>0){
            JSONObject object = new JSONObject();
            object.put("您上传的业务号码有重复，请确认！",isRecur);
            return JSON.toJSONString(object);
        }
        List<List<String>> list = new ArrayList<>();
        list = ExcelImport.queryRepetition(sheet,2);//第2列是计费号码
        List<Map<String,Object>> list1 = new ArrayList<>();
        for (int i = 0; i <list.size() ; i++) {
            list1.addAll(mapper.queryRepetition(list.get(i)));
        }
        if(list1.size()>0){
            return JSON.toJSONString(list1);
        }
//        List<List<String>> listC = ExcelImport.queryRepetition(sheet,0);//第0列是合同号码
//        List<Map<String,Object>> listContract = new ArrayList<>();
//        List<Map<String,Object>> notInRelationList = new ArrayList<>();
//
//        for (int i = 0; i <listC.size() ; i++) {
//            listContract.addAll(mapper.queryContractNumber(listC.get(i)));
//        }
//        List<String> listIn = new ArrayList<>();
//        for (int i = 0; i <listContract.size() ; i++) {
//            Map<String, Object> map = listContract.get(i);
//            String contract_no_global = map.get("CONTRACT_NO_GLOBAL").toString();
//            listIn.add(contract_no_global);
//        }
//        if(listContract.size()>0){
//            return JSON.toJSONString(list1);
//        }
            List<List<NMContractNew>> lists =listNmMobile(sheet,staffId);
            int size = lists.size();
            for (int i = 0; i <size ; i++) {
                List<NMContractNew> listI = lists.get(i);
                asyncService.executeContractRealationSerial(listI);
            }

        return "上传成功";
    }

    /**
     * 导入合同与业务号码关系
     *
     * @param sheets 合同与业务号码关系
     * @return
     */
    public List<List<NMContractNew>> listNmMobile(Sheet sheets,String staffId) throws Exception {
        List<List<NMContractNew>> lists =new ArrayList<>();
        List<NMContractNew> list = new ArrayList<>();
        Cell cell = null;
        for (int j = sheets.getFirstRowNum() + 1; j <= sheets.getLastRowNum()+1; j++) {
            Row row = sheets.getRow(j);
            int flag =200;
            if(list.size() !=0 && list.size()%flag ==0 || j == sheets.getLastRowNum()+1){
                List<NMContractNew> copy = new ArrayList<>(list);
                lists.add(copy);
                list.clear();
            }
            if (row == null || row.getFirstCellNum() == j) {
                continue;
            }else if (ExcelImport.isAllRowEmpty(row,row)){
                continue;
            }
            NMContractNew mobileService = new NMContractNew();
            for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                cell = row.getCell(y);
                if(cell==null || cell.toString().equals("")){
                    continue;
                }
                switch (y){
                    case 0 :mobileService.setContractNoGlobal(ExcelImport.getCellValue(cell)); break;
                    case 1:mobileService.setContractName(ExcelImport.getCellValue(cell)); break;
                    case 2:mobileService.setSerialNumber(ExcelImport.getCellValue(cell)); break;
                }

            }
            mobileService.setInputStaffId(staffId);
            mobileService.setUpdateStaffid(staffId);
            list.add(mobileService);
        }
        return lists;
    }
}
